<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NAvatar,
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect, NSelect, NFlex, useMessage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import {formatDate, getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'
const base_path = import.meta.env.VITE_BASE
import default_image from "@/assets/images/mz.jpg"

defineOptions({ name: '卡项' })
const instance = getCurrentInstance();
const nameFromInstance = instance?.type.name;

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const message = useMessage()

const data = reactive({
  uploadAction: base_path+'/system/base/userimg',
  token: getToken(),
  data_ini:{
    type: [],
    type1: [],
    category_id:[],
    cdp_type:[]
  },
  drug_all:[],
  config:[],
  level1:[],
  level2:[],
  type_names:[
    {"id":0,"name":"套餐"},
    {"id":100,"name":"会员卡"},
    {"id":88,"name":"品项"},
    {"id":99,"name":"储值"},
  ],
  vip_rules2_type:[
    {"id":1,"name":"百分比"},
    {"id":2,"name":"固定金额"}
  ]
})

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '卡项',
  initForm: {},
  doCreate: api.createCard,
  doUpdate: api.updateCard,
  doDelete: api.deleteCard,
  refresh: () => $table.value?.handlerefresh(),
})


onMounted(() => {
  $table.value?.handleSearch()
  api.getProjectIni().then((res) => (data.data_ini = res.data))
  api.getConfig().then((res) => {
     data.config = res.data
  })
})

const columns = [
  {
    title: 'ID',
    key: 'id',
    width:40,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '分类',
    key: 'type',
    width: 60,
    align: 'center',
    render(row) {
      return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.type_name })
    },
  },{
    title: '类型',
    key: 'category_name',
    width: 60,
    align: 'center',
    render(row) {
      return h(NTag, { type: 'error',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.category_name })
    },
  },


    {
    title: '图片/卡项名称',
    key: 'image',
    width: '200',
    align: 'left',
      fixed: 'left',

    render(row) {

      return h(NFlex, {},
        [h(NAvatar, {
          src: row.image,
          fallbackSrc: default_image,
          round: true,
          size: "medium",
        }), h(NButton, {
          size: "medium",
          dashed: true,
          type: "primary",
        }, {
          default: () => (row.title)
        })]
      )

    },
  },
  {
    title: '单价',
    key: 'price',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '上架状态',
    key: 'status',
    width: 50,
    align: 'center',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row.status,
        checkedValue: 1,
        uncheckedValue: 0,
        onUpdateValue: () => handleUpdateDisable(row),
      })
    },
  },
    {
    title: '积分规则',
    key: 'cdp_nums_name',
    width: 70,
    align: 'center',
  },{
    title: '销售|编导|打版',
    key: 'uid_price_name',
    width: 80,
    align: 'center',
  },
  {
    title: '操作',
    key: 'actions',
    width: 120,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                on_edit(row)
              },
            },
            {
              default: () => '编辑',
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          []
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ id: row.id }, false),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                  },
                  {
                    default: () => '删除',
                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                []
              ),
            default: () => h('div', {}, '确定删除该数据吗?'),
          }
        ),
      ]
    },
  },
]

// 修改用户禁用状态
async function handleUpdateDisable(row) {
  if (!row.id) return
  row.status = row.status === 1 ? 0 : 1
  try {
    await api.updateCard(row)
    $message?.success(row.status ? '已上架' : '已下架')
    $table.value?.handlerefresh()
  } catch (err) {
    // 有异常恢复原来的状态
    row.status = row.status === 1 ? 0 : 1
  }
}

const validateAddUser = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: ['input', 'blur'],
    },
  ],
}

const customRequestMethod = (options) => {
    console.log(options, 'options');
    const { file } = options.file;
    const formData = new FormData();
    formData.append('file', file);
    fetch(data.uploadAction, {
        method: 'POST',
        headers: options.headers,
        body: formData,
    })
        .then((response) => response.json())
        .then((data) => {
            console.log(data, 'datatat');
            if (data.code === 200) {
                modalForm.value.image = data.data.url
                message.success('封面图上传成功');
                options.onProgress(data);
            } else {
                message.error(data.msg);
            }
        })
}


const onCreate = () => {
  return {
    id: '',
    bl:'',
  }
}

const onCreate2 = () => {
  return {
    id: '',
    bl:'',
    type:1
  }
}
function on_add(){
  handleAdd()
  modalForm.value.status = 1
  modalForm.value.uid_price = 100
  modalForm.value.face_price = 100
  modalForm.value.doctor_price = 100
  get_drug_all()
}

function on_edit(row){
  handleEdit(row)
  get_drug_all()
}

function get_drug_all(){
  if(data.drug_all.length===0){
    api.getProjectsAllTree().then((res) => (data.drug_all = res.data))
  }
}

function handleMustChange(item, checked) {
  // 当设置为非必选时，将frequency设置为0
  if (checked === 0) {
    item.frequency = 0
  }
}
</script>

<template>
  <NLayout has-sider wh-full>
    <NLayoutContent style="background: transparent;margin-left: 20px;">
      <CommonPage show-footer :title="nameFromInstance+'列表'">
        <template #action>
          <NButton  type="primary" @click="on_add">
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建{{ nameFromInstance }}
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getCardList"
           :scroll-x="1400"
        >
          <template #queryBar>
            <QueryBarItem :label="nameFromInstance+'名称'" :label-width="80">
              <NInput
                v-model:value="queryItems.title"
                clearable
                type="text"
                placeholder="请输入名称"
                @keypress.enter="$table?.handleSearch()"
              />
            </QueryBarItem>

            <QueryBarItem label="套餐类型" :label-width="80">
              <NSelect
                v-model:value="queryItems.category_id"
                clearable
                :options="data.type_names"
                placeholder="请选择类型"
                label-field="name"
                value-field="id"
                style="width: 200px;"
              />
            </QueryBarItem>

          </template>
        </CrudTable>

        <!-- 新增/编辑 弹窗 -->
        <CrudModal
          v-model:visible="modalVisible"
          :title="modalTitle"
          :loading="modalLoading"
          @save="handleSave"
          style="width: 1500px;min-height: 700px"
        >
          <NForm
            ref="modalFormRef"
            label-placement="left"
            label-align="left"
            :label-width="80"
            :model="modalForm"
            :rules="validateAddUser"
          >
            <n-tabs type="line" animated size="large" pane-style="padding: 20px 0 0 0;">
              <n-tab-pane name="基础信息">
                <NFormItem label="分类" path="type">
                  <NSelect
                    v-model:value="modalForm.type"
                    :options="data.data_ini.type"
                    placeholder="请选择类型"
                    label-field="name"
                    value-field="id"
                  />
                </NFormItem>
                <NFormItem label="其它分类" path="type1">
                  <NSelect
                    v-model:value="modalForm.type1"
                    :options="data.data_ini.type1"
                    placeholder="请选择类型"
                    label-field="name"
                    value-field="id"
                  />
                </NFormItem>
                <NFormItem label="类型" path="category_id">
                  <NSelect
                    v-model:value="modalForm.category_id"
                    :options="data.type_names"
                    placeholder="请选择类型"
                    label-field="name"
                    value-field="id"
                  />
                </NFormItem>

                <NFormItem label="级别" path="up_level" v-if="modalForm.category_id===100">
                  <NSelect
                    v-model:value="modalForm.up_level"
                    :options="data.config.user_level"
                    placeholder="请选择升级到的级别"
                    label-field="name"
                    value-field="id"
                  />
                </NFormItem>
                <NFormItem label="名称" path="title">
                  <NInput v-model:value="modalForm.title" clearable placeholder="请输入名称" />
                </NFormItem>
                <NFormItem label="价格" path="price">
                  <NInputNumber  min="0" style="width: 100%"   v-model:value="modalForm.price" placeholder="请输入价格" />
                </NFormItem>
                <NFormItem label="过期天数" path="expire_day">
                  <NInputNumber  min="0" style="width: 100%"   v-model:value="modalForm.expire_day" placeholder="请输入天数" />
                </NFormItem>
                <NFormItem label="上架状态" path="status">
                  <NSwitch
                    v-model:value="modalForm.status"
                    :checked-value="1"
                    :unchecked-value="0"
                  />
                </NFormItem>
                <NFormItem label="封面图" path="image" style="width:100%">
                    <NImage v-if="modalForm.image" width="60" style="border-radius: 5px;margin-right: 15px;"
                        :src="modalForm.image"></NImage>
                    <NUpload :action="data.uploadAction" :headers="{ authorization: data.token }" :max="1"
                        :show-file-list=false :custom-request="customRequestMethod" list-type="image">
                        <NButton>上传</NButton>
                    </NUpload>
                </NFormItem>
              </n-tab-pane>
              <n-tab-pane name="关联品项">
                <NFormItem label="关联品项" path="card_project">
                  <n-layout>
                        <n-layout-header>
                          <n-flex >
                            <n-tag size="large" style="width: 800px"> 包含品项 </n-tag>
                            <n-tag size="large" style="width: 100px"> 可用次数 </n-tag>
                            <n-tag size="large" style="width: 70px"> 是否必选 </n-tag>
                          </n-flex>
                        </n-layout-header>
                        <n-layout-content content-style="padding: 10px 0;">
                          <n-dynamic-input v-model:value="modalForm.card_project" :on-create="onCreate">
                            <template #default="{ value , index}">
                              <n-flex justify="space-between">
<!--                                <NSelect-->
<!--                                  v-model:value="value.project_id"-->
<!--                                  :options="data.drug_all"-->
<!--                                  placeholder="请选择关联品项"-->
<!--                                  filterable-->
<!--                                  label-field="name"-->
<!--                                  value-field="id"-->
<!--                                  style="width: 250px"-->
<!--                                />-->
                                <n-cascader style="width: 800px;" v-model:value="value.project_id"
                                  check-strategy="child"
                                  clearable
                                  children-field="child"
                                  placeholder="请选择项目"
                                  :options="data.drug_all"
                                  label-field="name"
                                  value-field="id"
                                  show-path
                                  filterable
                                />
                                <n-input-number 
                                  min="0" 
                                  placeholder="请输入次数" 
                                  v-model:value="value.frequency" 
                                  style="width: 100px"
                                  :disabled="value.is_must === 0"
                                />
                                <NSwitch
                                  v-model:value="value.is_must"
                                  :checked-value="1"
                                  :unchecked-value="0"
                                  :default-value="1"
                                  size="large"
                                  style="width: 70px"
                                  @update:value="(checked) => handleMustChange(value, checked)"
                                />
                              </n-flex>
                            </template>
                          </n-dynamic-input>
                        </n-layout-content>
                      </n-layout>
                </NFormItem>
                <NFormItem label="可选数量" path="card_project">
                  <n-input-number   placeholder="没有可选不用填" v-model:value="modalForm.nums_select" style="width: 100%"/>
                </NFormItem>
               </n-tab-pane>
              <n-tab-pane name="积分规则">
                <NFormItem label="获得方式" path="cdp_type">
                  <NSelect
                    v-model:value="modalForm.cdp_type"
                    :options="data.data_ini.cdp_type"
                    placeholder="请选择获得方式"
                    label-field="name"
                    value-field="id"
                  />
                </NFormItem>
                <NFormItem label="获得数量" path="cdp_nums">
                  <NInputNumber v-model:value="modalForm.cdp_nums" min="0" clearable placeholder="请输入获得数量" />
                </NFormItem>
              </n-tab-pane>
              <n-tab-pane name="业绩规则">
                <NFormItem label="销售比例" path="uid_price">
                  <NInputNumber v-model:value="modalForm.uid_price" min="0" clearable placeholder="销售业绩比例" />
                </NFormItem>
                <NFormItem label="健康顾问比例" path="face_price">
                  <NInputNumber v-model:value="modalForm.face_price" min="0" clearable placeholder="编导业绩比例" />
                </NFormItem>
                <NFormItem label="打版比例" path="doctor_price">
                  <NInputNumber v-model:value="modalForm.doctor_price" min="0" clearable placeholder="打版业绩比例" />
                </NFormItem>
              </n-tab-pane>
              <n-tab-pane name="渠道分佣规则">
                 <NFormItem label="直属比例" path="vip_rules1">
                   <n-dynamic-input v-model:value="modalForm.vip_rules1" :min = "0" :max = "data.config.vip_level.length" :on-create="onCreate2">
                      <template #default="{ value }">
                        <div style="display: flex; align-items: center; width: 100%">
                          <NSelect
                          v-model:value="value.id"
                          :options="data.config.vip_level"
                          placeholder="请选择渠道等级"
                          filterable
                          label-field="name"
                          value-field="id"
                          style="margin-right: 10px;width: 200px"
                        />
                          <NSelect
                          v-model:value="value.type"
                          :options="data.vip_rules2_type"
                          placeholder="请选择分佣类型"
                          filterable
                          label-field="name"
                          value-field="id"
                          style="margin-right: 10px;width:200px"
                        />
                          <n-input-number
                            v-model:value="value.bl"
                            :show-button="false"
                            placeholder="百分比直接输入数字"
                          >
<!--                            <template #suffix>-->
<!--                                %-->
<!--                              </template>-->
                          </n-input-number>
                        </div>
                      </template>
                    </n-dynamic-input>
                </NFormItem>
                <NFormItem label="间接比例" path="vip_rules2">
                   <n-dynamic-input v-model:value="modalForm.vip_rules2" :min = "0" :max = "data.config.vip_level.length" :on-create="onCreate2">
                      <template #default="{ value }">
                        <div style="display: flex; align-items: center; width: 100%">
                          <NSelect
                          v-model:value="value.id"
                          :options="data.config.vip_level"
                          placeholder="请选择渠道等级"
                          filterable
                          label-field="name"
                          value-field="id"
                          style="margin-right: 10px;width:200px"
                        />

                          <NSelect
                          v-model:value="value.type"
                          :options="data.vip_rules2_type"
                          placeholder="请选择分佣类型"
                          filterable
                          label-field="name"
                          value-field="id"
                          style="margin-right: 10px;width:200px"
                        />
                          <n-input-number
                            v-model:value="value.bl"
                            :show-button="false"
                            placeholder="百分比直接输入数字"
                          >
<!--                            <template #suffix>-->
<!--                                %-->
<!--                              </template>-->
                          </n-input-number>
                        </div>
                      </template>
                    </n-dynamic-input>
                </NFormItem>
              </n-tab-pane>
            </n-tabs>
          </NForm>
        </CrudModal>
      </CommonPage>
    </NLayoutContent>
  </NLayout>
  <!-- 业务页面 -->
</template>
